package com.zyd.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.zyd.constants.ErrorDef;
import com.zyd.constants.SessionKeyConstants;
import com.zyd.exception.BusinessException;
import com.zyd.io.model.RolePowerEntity;
import com.zyd.io.model.UserEntity;
import com.zyd.io.model.UserEntityExample;
import com.zyd.io.model.UserEntityKey;
import com.zyd.io.page.PageBean;
import com.zyd.io.vo.page.MultiQueryPageVO;
import com.zyd.io.vo.user.LoginRequestVO;
import com.zyd.io.vo.user.ModifyPasswdVO;
import com.zyd.io.vo.user.UserVO;
import com.zyd.mappers.UserEntityMapper;
import com.zyd.service.power.PowerService;
import com.zyd.service.user.UserService;
import com.zyd.util.FieldMapping;
import com.zyd.util.SqlUtils;
import com.zyd.util.ToolUtils;
import com.zyd.util.UUIDUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import com.zyd.context.HeaderContext;

import javax.servlet.http.HttpSession;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

@Component
public class UserServiceImpl implements UserService, InitializingBean {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

    private FieldMapping fieldMapping;

    @Autowired
    private UserEntityMapper mapper;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private PowerService powerService;

    @Override
    public UserEntity findUser(String id) {
        UserEntityKey userEntityKey = new UserEntityKey();
        userEntityKey.setId(id);
        return mapper.selectByPrimaryKey(userEntityKey);
    }

    @Override
    public PageBean<UserEntity> findUserList(MultiQueryPageVO request) {
        String uid=(String) HeaderContext.get().get("userid");

        String countSql = "select count(*)";
        String selectFields = "select * ";
        StringBuilder sql = new StringBuilder();
        sql.append("from zydzn_users where dr = 0 and createuser like '%"+uid+"%'");
        sql.append(SqlUtils.addMultiCondition(request.getSearchKeys(), fieldMapping));
        Long totalRows = jdbcTemplate.queryForObject(countSql + sql.toString(), Long.class);
        String pageSql = SqlUtils.addPage(selectFields + sql.toString(), request.getCurrentPage(), request.getPageSize());

        List<UserEntity> ret = jdbcTemplate.query(pageSql, new RowMapper<UserEntity>() {

            @Override
            public UserEntity mapRow(ResultSet rs, int rowNum) throws SQLException {
                UserEntity userEntity = SqlUtils.mappingToBean(rs, UserEntity.class);
                return userEntity;
            }
        });

        PageBean<UserEntity> pageBean = new PageBean<UserEntity>(request.getCurrentPage(), request.getPageSize(), totalRows.intValue());
        pageBean.setItems(ret);
        return pageBean;
    }



    @Override
    public void updateUser(UserEntity user) {
        //checkUserNameExist(user);
        user.setTs(ToolUtils.getNowTime());

        mapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public void deleteUser(String id) {
        UserEntity userEntity = new UserEntity();
        userEntity.setId(id);
        userEntity.setDr(1);
        userEntity.setTs(ToolUtils.getNowTime());

        mapper.updateByPrimaryKeySelective(userEntity);
    }

    @Override
    public void insertUser(UserEntity user) {
        String uid=(String) HeaderContext.get().get("userid");

        user.setTs(ToolUtils.getNowTime());
        user.setDr(0);
        checkUserNameExist(user);
        user.setId(UUIDUtil.getUUid());
        user.setPwd(ToolUtils.encodePasswd("Admin123"));
        user.setCreateuser(uid);
        mapper.insertSelective(user);
    }

    @Override
    public void motifyPasswd(ModifyPasswdVO modifyPasswdRequest) {
        UserEntityKey key = new UserEntityKey();
        key.setId(modifyPasswdRequest.getUserid());

        UserEntity user = mapper.selectByPrimaryKey(key);
        LOGGER.info("用户密码:" + user.getPwd());
        LOGGER.info("原密码:" + modifyPasswdRequest.getOldpwd());
        if (!user.getPwd().equals(ToolUtils.encodePasswd(modifyPasswdRequest.getOldpwd()))) {
            throw new BusinessException(ErrorDef.UPLOAD_IMG_ERROR, ErrorDef.OLD_PASSWDF_NOT_SAMPLE_ERROR_MSG);
        }


        UserEntity modifyUser = new UserEntity();
        modifyUser.setId(modifyPasswdRequest.getUserid());
        modifyUser.setPwd(ToolUtils.encodePasswd(modifyPasswdRequest.getNewpwd()));
        mapper.updateByPrimaryKeySelective(modifyUser);
    }

    @Override
    public Map<String, Object> login(LoginRequestVO requestVO, HttpSession session) {
        UserEntityExample example = new UserEntityExample();
        UserEntityExample.Criteria criteria = example.or().andUsernameEqualTo(requestVO.getUsername());
        System.out.println("用户名"+requestVO.getUsername());

        long l = mapper.countByExample(example);
        if (l == 0) {
            criteria=example.or().andMobileEqualTo(requestVO.getUsername());
            l = mapper.countByExample(example);
            if (l == 0) {
                throw new BusinessException(ErrorDef.LOGIN_USER_NAME_NOT_EXIST_ERROR, "用户不存在");
            }
        }

        criteria.andPwdEqualTo(ToolUtils.encodePasswd(requestVO.getPasswd()));

        l = mapper.countByExample(example);
        if (l == 0) {
            throw new BusinessException(ErrorDef.SYSTEM_ERROR, "密码不正确");
        }

        List<UserEntity> users = mapper.selectByExample(example);
        UserEntity user = users.get(0);
		System.out.println("角色id"+user.getUsertype());
        Map<String, Object> menus = powerService.queryPowsersByRoleId(user.getUsertype());

        Map<String, Object> ret = Maps.newHashMap();
        UserVO userVO = new UserVO();
        userVO.setCity(user.getCity());
        userVO.setId(user.getId());
        userVO.setPhone(user.getMobile());
        userVO.setNickname(user.getNickname());
        userVO.setUsername(user.getUsername());
        userVO.setPassword(user.getPwd());
        userVO.setRoleid(user.getUsertype());

        ret.put("user", userVO);
        ret.putAll(menus);

        session.setAttribute(SessionKeyConstants.LOGIN_USER, JSON.toJSONString(ret));
        LOGGER.info("保存session信息" + JSON.toJSONString(ret));
        return ret;
    }

    private void checkUserNameExist(UserEntity user) {
        UserEntityExample example = new UserEntityExample();
        example.or().andUsernameEqualTo(user.getUsername()).andDrEqualTo(0);
        long count = mapper.countByExample(example);
        if (count > 0) {
            throw new BusinessException(ErrorDef.USER_NAME_EXIST_ERROR, ErrorDef.USER_NAME_EXIST_ERROR_MSG);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.fieldMapping = new FieldMapping();
        fieldMapping.addMapping("mobile", "phone");
        fieldMapping.addMapping("pwd", "password");
        fieldMapping.addMapping("usertype", "roleid");
    }

    @Override
    public String findValidatecode(String username) {
        String findSql = "select code from zydzn_validatecode where phone='"+username+"' order by id desc ";
        System.out.println(findSql);
        List<String> ret = jdbcTemplate.query(findSql, new RowMapper<String>() {
            @Override
            public String mapRow(ResultSet rs, int rowNum) throws SQLException {
                System.out.println(rs.getString("code"));
                return  rs.getString("code");
            }
        });


        return ret.get(0);
    }
    @Override
    public void setValidatecode(String username,String code) {
        String sql = "insert into  zydzn_validatecode (phone,code) values('"+username+"','"+code+"') ";
        jdbcTemplate.batchUpdate(sql);

    }

    @Override
    public String findMobilebyusername(String username) {
        String findSql = "select mobile from zydzn_users where username='"+username+"' or mobile='"+username+"'  ";
        System.out.println(findSql);
        List<String> ret = jdbcTemplate.query(findSql, new RowMapper<String>() {
            @Override
            public String mapRow(ResultSet rs, int rowNum) throws SQLException {
                System.out.println(rs.getString("mobile"));
                return  rs.getString("mobile");
            }
        });


        return ret.get(0);
    }



    /**
     * 重置密码
     * @param id 需要重置密码的用户的id
     */
    @Override
    public void resetPassword(String id) {
        try{
            String userid = (String) HeaderContext.get().get("userid");
            RolePowerEntity rolePowerEntity = powerService.queryPowerListByUserId(userid, "9023");
            if (rolePowerEntity==null) {
                throw new BusinessException("权限不足");
            }
        }catch (Exception e){
            throw new BusinessException("权限不足");
        }

        String admin123 = ToolUtils.encodePasswd("Admin123");
        jdbcTemplate.update("UPDATE zydzn_users SET pwd= ? WHERE id = ?",admin123,id );
    }

}
